<template>
  <div class="speech-container">
    <!-- 左右布局容器 -->
    <div class="content-wrapper">
      <!-- 左侧：语音转文字结果展示区 -->
      <div class="result-section">
        <h3 class="section-title">
          <i class="el-icon-microphone"></i> 语音识别结果
        </h3>
        <el-input
          type="textarea"
          autosize
          v-model="result"
          rows="12"
          placeholder="点击「开始录音」，说话后会显示识别结果（仅支持 Chrome 等现代浏览器）"
          readonly
          class="result-textarea"
        ></el-input>
      </div>

      <!-- 右侧：文字输入与播放区 -->
      <div class="text-section">
        <h3 class="section-title">
          <i class="el-icon-volume-2"></i> 文字转语音
        </h3>

        <el-input
          type="textarea"
          autosize
          v-model="textToSpeak"
          rows="12"
          placeholder="请输入文字，点击「开始播放」进行语音朗读"
          class="input-textarea"
        ></el-input>
      </div>
    </div>

    <!-- 控制按钮区域 -->
    <div class="control-buttons">
      <el-button
        type="primary"
        icon="el-icon-microphone"
        @click="startRecognition"
        :disabled="isRecognizing || isSpeaking"
        class="control-btn"
      >
        {{ isRecognizing ? "识别中..." : "开始录音" }}
      </el-button>
      <el-button
        type="danger"
        icon="el-icon-stop"
        @click="stopAll"
        :disabled="!isRecognizing && !isSpeaking"
        class="control-btn"
      >
        停止
      </el-button>
      <el-button
        type="success"
        icon="el-icon-volume-2"
        @click="startSpeaking"
        :disabled="isSpeaking || isRecognizing || !textToSpeak.trim()"
        class="control-btn"
      >
        {{ isSpeaking ? "播放中..." : "开始播放" }}
      </el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: "SpeechRecognitionNative",
  data() {
    return {
      // 语音转文字相关
      result: "",
      isRecognizing: false,
      recognition: null,

      // 文字转语音相关
      textToSpeak: "",
      isSpeaking: false,
      speechSynthesis: window.speechSynthesis,
      utterance: null,
    };
  },
  mounted() {
    const browser = navigator.userAgent.toLowerCase();
    if (browser.includes("chrome") && !browser.includes("edge")) {
      this.$message.info(
        "Chrome 浏览器可能需要联网访问语音服务，若识别失败可尝试其他浏览器"
      );
    }
    // 初始化语音识别
    this.initSpeechRecognition();
    // 初始化语音合成
    this.initSpeechSynthesis();
  },
  methods: {
    // 初始化语音识别
    initSpeechRecognition() {
      if (window.SpeechRecognition || window.webkitSpeechRecognition) {
        this.recognition = new (window.SpeechRecognition ||
          window.webkitSpeechRecognition)();
        this.recognition.continuous = true;
        this.recognition.interimResults = true;
        this.recognition.lang = "zh-CN";

        this.recognition.onresult = (event) => {
          let interimTranscript = "";
          let finalTranscript = "";
          for (let i = event.resultIndex; i < event.results.length; i++) {
            const transcript = event.results[i][0].transcript;
            if (event.results[i].isFinal) {
              finalTranscript += transcript;
            } else {
              interimTranscript += transcript;
            }
          }
          this.result = finalTranscript || interimTranscript;
        };

        this.recognition.onerror = (event) => {
          console.error("语音识别错误:", event.error);
          // 针对 network 错误的提示
          if (event.error === "network") {
            this.$message.error(
              "网络错误：请检查网络连接，确保使用 HTTPS 环境（localhost 除外）"
            );
            
          } else if (event.error === "not-allowed") {
            this.$message.error("权限被拒绝：请在浏览器设置中允许麦克风访问");
          } else {
            this.$message.error("语音识别出错：" + event.error);
          }
          this.isRecognizing = false;
        };

        this.recognition.onend = () => {
          this.isRecognizing = false;
        };
      } else {
        this.$message.warning(
          "您的浏览器不支持 Web Speech API，无法使用语音功能"
        );
      }
    },

    // 初始化语音合成
    initSpeechSynthesis() {
      this.utterance = new SpeechSynthesisUtterance();
      this.utterance.lang = "zh-CN";
      this.utterance.rate = 1; // 语速
      this.utterance.volume = 1; // 音量
      this.utterance.pitch = 1; // 音调

      this.utterance.onend = () => {
        this.isSpeaking = false;
      };

      this.utterance.onerror = (event) => {
        console.error("语音合成错误:", event.error);
        this.$message.error("语音播放出错：" + event.error);
        this.isSpeaking = false;
      };
    },

    // 开始录音识别
    startRecognition() {
      if (!this.recognition) return;
      this.isRecognizing = true;
      this.result = "正在初始化语音识别，请开始说话...";
      this.recognition.start();
    },

    // 开始文字转语音播放
    startSpeaking() {
      if (!this.utterance || this.isSpeaking) return;

      this.isSpeaking = true;
      this.utterance.text = this.textToSpeak;
      this.speechSynthesis.speak(this.utterance);
    },

    // 停止所有操作
    stopAll() {
      // 停止语音识别
      if (this.recognition && this.isRecognizing) {
        this.recognition.stop();
        this.isRecognizing = false;
      }

      // 停止语音播放
      if (this.speechSynthesis.speaking) {
        this.speechSynthesis.cancel();
        this.isSpeaking = false;
      }
    },
  },
  beforeDestroy() {
    this.stopAll();
  },
};
</script>

<style scoped>
.speech-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 15px;
}

.content-wrapper {
  display: flex;
  gap: 20px;
  width: 100%;
}

.result-section,
.text-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.section-title {
  margin: 0;
  font-size: 16px;
  color: #333;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
}

.result-textarea {
  background-color: #f9f9f9;
  resize: none;
}

.input-textarea {
  resize: none;
}

.control-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
  padding-top: 10px;
}

.control-btn {
  min-width: 140px;
}
</style>
